<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Service;
use fast\Http;
use think\Log;

class Nav extends Api
{
    protected $noNeedRight = '*';
    protected $noNeedLogin = '*';

    /**
     * 首页栏目
     *
     * @param \app\common\model\Nav $nav
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(\app\common\model\Nav $nav)
    {
        $this->success(
            '',
            $nav
                ->where('status', 1)
                ->where('show_index', 1)
                ->where('pid', '>', 0)
                ->order('weigh desc')
                ->select()
        );
    }

    /**
     * 服务类目
     *
     * @param \app\common\model\Nav $nav
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function category(\app\common\model\Nav $nav)
    {
        $this->success(
            '',
            $nav
                ->with(['items'])
                ->where('status', 1)
                ->where('pid', 0)
                ->order('weigh desc')
                ->select()
        );
    }

    /**
     * 服务列表
     *
     * @param Service $service
     * @return void
     */
    public function lists(Service $service)
    {
        $this->success(
            '',
            $service
                ->where('second', $this->request->get('category_id', 0))
                ->order('weigh desc')
                ->paginate(10)
        );
    }

    /**
     * 服务详情
     *
     * @param Service $service
     * @return void
     * @throws \think\exception\DbException
     */
    public function detail(Service $service)
    {
        if (!$info = $service::get($this->request->get('id', 0))) {
            $this->error('服务不存在');
        }
        $this->success(
            '',
            $info
        );
    }

    /**
     * 首页板块
     *
     * @param \app\common\model\Nav $nav
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function first(\app\common\model\Nav $nav, Service $service)
    {
        $lists = $nav
            ->where('pid', 0)
            ->where('show_index', 1)
            ->where('status', 1)
            ->order('weigh desc')
            ->select();
        foreach ($lists as &$item) {
            $item['services'] = $service->where([
                'status' => 'normal',
                'first' => $item['id']
            ])->order('weigh desc')->limit(3)->select();
        }
        //查询一级大类
        $this->success(
            '',
            $lists
        );
    }

    /**
     * 首页板块-二级
     *
     * @param \app\common\model\Nav $nav
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function second(\app\common\model\Nav $nav)
    {
        $this->success(
            '',
            $nav
                ->where('pid', $this->request->get('id', 0))
                ->order('weigh desc')
                ->select()
        );
    }

    /**
     * 首页板块-更多
     *
     * @param Service $service
     * @return void
     * @throws \think\exception\DbException
     */
    public function more(
        Service $service,
        \app\common\model\Nav $nav
    )
    {
        if (!$info = $nav::get($this->request->get('id', 0))) {
            $this->error('分类不存在');
        }
        $where['status'] = 'normal';
        if ($info['pid']) {
            $where['second'] = $info['id'];
        } else {
            $where['first'] = $info['id'];
        }
        $this->success(
            '',
            $service
                ->where($where)
                ->order('weigh desc')
                ->paginate(10)
        );
    }

    /**
     * 获取海报
     *
     * @return void
     */
    public function poster()
    {
        $id = $this->request->get('id', 0);
        $result = self::getQrcode($this->auth->getUser(), 'pages/index/proPage/detailes')['data'] ?? '';
        $this->success(
            '',
            $result
        );
    }

    /**
     * 获取小程序二维码
     *
     * @param $user
     * @param $path
     * @param $scene
     * @return array
     */
    public function getQrcode($user, $service_id, $path = null, $scene = null)
    {
//        if ($user->qr_image) {
//            return [
//                'code' => 0,
//                'data' => cdnurl($user->qr_image, true),
//            ];
//        }
        $userId = $user->id ?? 0;
        $token = (new Wechat())->getAccessToken()['access_token'];
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$token}";
        $data = json_encode([
            'scene' => $scene ? $scene : "$userId&$service_id",
            'page' => $path ? trim($path, '/') : 'pages/index/index',
            'width' => 246,
            'check_path' => false,
            // 'env_version'=>'trial'
        ]);
        $http = new Http();

        $response = $http->post($api, $data);
        $json_response = json_decode($response, true);
        if (!is_array($json_response)) {
            $file = self::saveTempImageByContent($response);
            if (!file_exists($file)) {
                return [
                    'code' => 1,
                    'msg' => '二维码保存失败',
                ];
            }
//            $user->qr_image =  '/' . $file;
//            $user->save();
            return [
                'code' => 0,
                'data' => cdnurl('/' . $file, true),
            ];
        } else {
            Log::write('二维码生成失败:' . json_encode($json_response), 'error');
            //返回文字
            // $res = json_decode($response, true);
            return [
                'code' => 1,
                'msg' => $json_response['errmsg'],
            ];
        }
    }

    public function saveTempImageByContent($content)
    {
        $dir1 = ROOT_PATH . 'public/uploads/service_qrcode/';
        if (!is_dir($dir1)) @mkdir($dir1, 0700);
        $save_name = md5(base64_encode($content)) . '.jpg';
        $save_path = 'uploads/service_qrcode/' . $save_name;
        $fp = fopen($dir1 . $save_name, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }
}